package com.atguigu.gmall.rabbit.component.impl;

import com.atguigu.gmall.common.util.JsonUtil;
import com.atguigu.gmall.common.util.MD5;
import com.atguigu.gmall.rabbit.component.RabbitService;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.io.IOException;

/**
 * @Author:lyd
 **/
@Service
@Slf4j
public class RabbitServiceImpl implements RabbitService {

    @Autowired
    RabbitTemplate rabbitTemplate;
    @Autowired
    StringRedisTemplate redisTemplate;

    @Override
    public void sendMsg(String exchange, String routingKey, Object msg) {
        String jsonStr = JsonUtil.objToJsonStr(msg);
        rabbitTemplate.convertAndSend(exchange, routingKey, jsonStr);
    }

    @Override
    public void retry(Message message, Channel channel,int count) throws IOException {
        long deliveryTag = message.getMessageProperties().getDeliveryTag();
        String msgStr = new String(message.getBody());
        String encryptMsg = MD5.encrypt(msgStr);
        Long increment = redisTemplate.opsForValue().increment("msg:count:" + encryptMsg);
        if (increment <= count) {
            channel.basicReject(deliveryTag,true);
        }else {
            //重试5次还不能消费消息，手动确认接收消息，把消息保存数据库人工处理
            channel.basicAck(deliveryTag, false);
            log.warn("消息重试5次消费失败，记录数据库，通知人工处理。。。消息内容：{}",msgStr);
            redisTemplate.delete("msg:count:" + encryptMsg);
        }
    }
}
